package statsyslogic

import (
	"context"
	"github.com/zeromicro/go-zero/core/mr"
	"go.uber.org/zap"
	"navi-mumbai/app/rpc/model/pg/stat"
	"navi-mumbai/common/key/dbkey"
	"navi-mumbai/common/utils"
	"navi-mumbai/common/xerr"
	"strconv"
	"time"

	"navi-mumbai/app/rpc/stat/internal/svc"
	"navi-mumbai/app/rpc/stat/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserDailyLoginStatLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserDailyLoginStatLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserDailyLoginStatLogic {
	return &UserDailyLoginStatLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 每日用户登陆数据统计
func (l *UserDailyLoginStatLogic) UserDailyLoginStat(in *pb.UserDailyLoginStatReq) (*pb.UserDailyStatLoginResp, error) {
	defer utils.RecoverPanic()

	var start, end *time.Time
	if in.StartTime != "" {
		loc, _ := time.LoadLocation(dbkey.DateTimeZone)
		t, err := time.ParseInLocation(dbkey.DateTimeCNFormat, in.StartTime, loc)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, err.Error())
		}
		start = &t
	}
	if in.EndTime != "" {
		loc, _ := time.LoadLocation(dbkey.DateTimeZone)
		t, err := time.ParseInLocation(dbkey.DateTimeCNFormat, in.EndTime, loc)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, err.Error())
		}
		end = &t
	}

	var ds stat.UserDailyLoginStat
	ds.StatDay, _ = strconv.ParseInt(start.Format(dbkey.DateFormat2), 10, 64)
	var err error

	err = mr.Finish(func() error {
		// 新用户
		ds.NewUserCount, err = l.svcCtx.UserAccountModel.Count(l.ctx, start, end)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
		}
		return nil
	},
		func() error {
			// 活跃用户
			ds.ActiveUserCount, err = l.svcCtx.UserLoginStatModel.CountLoginUser(l.ctx, start, end)
			if err != nil {
				l.Logger.Errorf("err == ", zap.Error(err))
			}
			return nil
		})
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
	}

	//
	_, err = l.svcCtx.UserDailyLoginStatModel.Insert(l.ctx, &ds)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, err
	}

	return &pb.UserDailyStatLoginResp{}, nil
}
